﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace Hydrogen.MarkovChain
{
    public abstract class RuleNodeBase
    {
        #region static
        protected static Dictionary<string, Type> _nodeTypeDic = null;
        /// <summary>
        /// 根据节点类型，创建节点对象
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public static RuleNodeBase Create(XmlNode node)
        {
            if (_nodeTypeDic == null)
            {
                var dic = RuleNodeNameAttribute.GetTypes(new System.Reflection.Assembly[] { typeof(RuleNodeBase).Assembly }, typeof(RuleNodeBase));
                _nodeTypeDic = new Dictionary<string, Type>();
                foreach (var item in dic)
                {
                    _nodeTypeDic[item.Key.Name] = item.Value;
                }
            }

            if (!_nodeTypeDic.TryGetValue(node.Name, out var type)) return null;
            return Activator.CreateInstance(type,node) as RuleNodeBase;
        }

        protected static List<RuleNodeBase> GetChildNode(XmlNode xmlNode, List<string> chileNodeTypes)
        {
            List<RuleNodeBase> result = new List<RuleNodeBase>();
            if (xmlNode == null) return result;

            foreach (XmlNode item in xmlNode.ChildNodes)
            {
                if (!chileNodeTypes.Contains(item.Name)) continue;
                var ruleNode = Create(item);
                if (ruleNode == null) continue;
                result.Add(ruleNode);
            }

            return result;
        }
        #endregion

        protected XmlNode _node;
        public RuleNodeBase(XmlNode node)
        {
            this._node = node;
        }

        public virtual void Reset() { }

    }
}
